package com.example.hydropowermanage.controller;

import com.example.hydropowermanage.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("")
public class ImageController {

    @Autowired
    private ImageService imageService;
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    // 设置存储上传头像的目录,修改成自己的img根路径
    private static final String UPLOAD_DIR =
            "D:\\my\\university\\temp\\2023-2\\web开发\\bigwork\\hydro\\hydroPowerManage\\src\\main\\resources\\static\\img";

    @PostMapping("/Avatar/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file,
                                                   @RequestParam("userId") int userId) {

        if (!file.isEmpty()) {
            logger.info("Upload file: " + file.getOriginalFilename());
            try {
                String filePath = UPLOAD_DIR + File.separator + file.getOriginalFilename();
                logger.info("File path: " + filePath);
                file.transferTo(new File(filePath));
                logger.info("Upload success");
                String newFilePath = "img/" + file.getOriginalFilename();
                imageService.updateAvaterurl(newFilePath, userId);
                return new ResponseEntity<>(filePath, HttpStatus.OK);

            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>("Upload failed", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            return new ResponseEntity<>("Upload failed", HttpStatus.BAD_REQUEST);
        }
    }

    @GetMapping("/{fileName:.+}")
    @ResponseBody
    public ResponseEntity<byte[]> serveFile(@PathVariable String fileName) {
        try {
            // 从uploads目录加载文件
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName);
            byte[] fileContent = Files.readAllBytes(filePath);

            return ResponseEntity.ok().body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.notFound().build();
        }
    }
}
